#!/bin/perl
# Author Edgar Medina
use Bio::SeqIO;
use Bio::DB::Fasta;
use strict;
use warnings;

#SCRIPT FOR INDEXING A LOCAL DATABASE PRIOR TO FETCHING SEQUENCES!!!!
 # assume that the argument are
# 1. Database name
# 2. IDs file
# so run this  like
# perl do_index+getseq.pl DBNAME IDFILENAME > retreived_seqs.fasta
# or run this like
# perl do_index+getseq.pl DIRECTORY_OF_SEQUENCES IDFILENAME > retreived_seqs.fasta

my ($dbname, $idsfile) = @ARGV;
my $db = Bio::DB::Fasta->new($dbname);
my $out = Bio::SeqIO->new(-fh => \*STDOUT, -format => 'fasta'); # our SeqIO fasta writer object
open(IDS, $idsfile) || die "cannot open file $idsfile: $!";
while(<IDS>) {
 # each line of the ID file has the ID from a species
 my ($id) = split;
 # if this ID is composite... like
 # Bden_JAM81|IDHERE
 # then you want to add some code

# if( $id =~ /\|/) { 
#  (undef,$id) = split(/\|/,$id);
# }
 # maybe more checks on the ID and cleaning it up next
 #

 # cleaned ID, let us fetch it from the database
 my $seq = $db->get_Seq_by_id($id);
 if( $seq ) {
   my $temp_id = $seq->id;
   # could fix the ID to remove any prefixes if you want
   if( $temp_id =~ /^jgi\|/) {
	my $tseq = Bio::Seq->new(-id => $seq->id,
                            -desc => $seq->description,
                            -seq => $seq->seq);
	my @row = split(/\|/,$temp_id); 
   	 $seq = $tseq;
        $temp_id = $row[1] . '_' . $row[-1]; # -1 means the LAST one 
        $seq->id($temp_id);
   }
   $out->write_seq($seq); 
 } else {
   warn("Cannot find sequence '$seq' in the db, did you parse the ID properly?\n");
 }
}
close IDS;

# put subroutines here

